package com.zlq.cn.util.des.hash;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class HrMD5 {

	/** IO缓冲区长度. */
	private static final int READBUF_SIZE = 1024;

	/** 计算消息摘要的对象. */
	private static MessageDigest messageDigest = null;

	static {
		try {
			messageDigest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			// 通常来说不会执行到这里
			e.printStackTrace();
		}
	}

	/**
	 * 获取字符串的Md5.
	 * 
	 * @param data
	 *            待计算MD5的字符串
	 * @return Md5的字节数组
	 * @throws Exception
	 *             输入参数不合法.
	 */
	public static byte[] getHashByString(String data) throws Exception {
		if (data == null) {
			// $ERROR:MPCM005==MD5计算输入参数为空==请联系客服
			throw new Exception("MPCM005");
		}

		try {
			return getHashByBytes(data.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// 通常来说不会执行到这里
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取字节数组的Md5.
	 * 
	 * @param data
	 *            待计算MD5的字节数组
	 * @return M5d的字节数组
	 * @throws Exception
	 *             输入参数不合法.
	 */
	public synchronized static byte[] getHashByBytes(byte[] data)
			throws Exception {
		if (data == null) {
			// $ERROR:MPCM006==MD5计算输入参数为空==请联系客服
			throw new Exception("MPCM006");
		}

		try {
			messageDigest.reset();
			messageDigest.update(data);
			return messageDigest.digest();
		} catch (Exception e) {
			return "".getBytes();
		}
	}

	/**
	 * 获取流的MD5.
	 * 
	 * @param is
	 *            待计算MD5的输入流
	 * @return M5d的16进制字符串
	 * @throws Exception
	 *             输入参数不合法.
	 * @throws Exception
	 *             输入输出错误.
	 */
	public static byte[] getHashByInputStream(InputStream is) throws Exception,
			Exception {
		if (is == null) {
			// $ERROR:MPCM007==MD5计算输入参数为空==请联系客服
			throw new Exception("MPCM008");
		}

		try {
			int size;
			byte[] buf = new byte[READBUF_SIZE];
			messageDigest.reset();
			while ((size = is.read(buf)) != -1) {
				messageDigest.update(buf, 0, size);
			}
			return messageDigest.digest();
		} catch (IOException e) {
			// $ERROR:MPCM008==MD5计算读取输入流时出现错误==请联系客服
			throw new Exception("MPCM008");
		}
	}
}
